package com.buss.core.persistence;

import java.io.Serializable;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map;

import com.buss.core.utils.StringUtil;

public class PersistenceCond implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 4676611900143160715L;
	
	private Map<String,Object> condition = new IdentityHashMap<String, Object>();
	
	/**
	 * 增加条件
	 * @param key
	 * @param value
	 */
	public void add(String key,Object value){
		if(StringUtil.isNotEmpty(key)){
			if(value == null) value = "";
			condition.put(new String(key), value);
		}
	}
	
	/**
	 * 删除条件
	 * @param key
	 */
	public void remove(String key){
		if(StringUtil.isNotEmpty(key)){
			condition.remove(key);
		}
	}
	
	/**
	 * 获取条件值
	 * @param key
	 * @return
	 */
	public Object getValue(String key){
		if(condition.get(key) != null){
			return condition.get(key);
		}else{
			return "";
		}
	}
	
	/**
	 * 合并条件
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String aggCondition(){
		Iterator iter = condition.entrySet().iterator();
		String key,val;
		String sql = "";
		int i = 1;
		while(iter.hasNext()){
			Map.Entry<String, Object> entry = (Map.Entry<String, Object>)iter.next();
			key = entry.getKey();
			val = transform(entry.getValue());
			if(i < condition.size()){
				sql += key + " = " + val + " and "; 
			}else{
				sql += key + " = " + val;
			}
			i++;
		}
		if(StringUtil.isNotEmpty(sql)){
			return sql;
		}
		return "";
	}
	
	/**
	 * 类型转换
	 * @param obj
	 * @return
	 */
	private String transform(Object obj){
		if(obj instanceof String){
			return "'" + obj.toString() + "'";
		}else{
			return obj.toString();
		}
	}
	
	
	
	public Map<String, Object> getCondition() {
		return condition;
	}

	public void setCondition(Map<String, Object> condition) {
		this.condition = condition;
	}

	public static void main(String[] args){

		PersistenceCond condition = new PersistenceCond();
		condition.add("name", null);
		condition.add("num", 100);
		condition.add("name", "1234");
		condition.add("123", "fdfd");
		System.out.println(condition.getValue("name") + "9999");
		System.out.println(condition.aggCondition());
		
	}
}
